package ac.github.os.internal.core.action.player

import ac.github.os.internal.core.action.IEntityAction
import ac.github.os.internal.core.config.StringConfig
import ac.github.os.internal.core.config.get
import ac.github.os.internal.core.objective.EntityObjective
import ac.github.os.internal.session.Cache
import ac.github.os.internal.session.Session
import org.bukkit.entity.Player
import taboolib.common.platform.Awake
import taboolib.common.platform.function.console

@Awake
class CommandAction : IEntityAction {
    override fun onExecute(session: Session, cache: Cache, config: StringConfig) {
        val type = config.get("type", "PLAYER")!!
        config.get<String>("val")?.let { string ->
            cache.filterIsPlayers().forEach { player ->
                when (type) {
                    "PLAYER" -> {
                        player.performCommand(string)
                    }
                    "CONSOLE" -> {
                        console().performCommand(string)
                    }
                    "OP" -> {
                        val op = player.isOp
                        player.isOp = true
                        try {
                            player.performCommand(string)
                        } catch (e: Exception) {
                        } finally {
                            player.isOp = op
                        }
                    }
                }
            }
        }
    }

    override val namespace: String
        get() = "player:command"
}